import React, { useState, useEffect } from 'react';
import { ArrowLeftOutlined, ArrowRightOutlined, StrikethroughOutlined } from '@ant-design/icons';
import { Toast } from 'antd-mobile';
import './AppointmentFrom.css';
import { useParams, useNavigate } from 'react-router-dom'; 
import { get_single_product_package } from '../../services/product'; // 接口
import Load from '../../components/Loading';

const BookingTime = () => {
  // 路由参数和导航
  const { id } = useParams();
  const navigate = useNavigate();
  
  // 状态管理 - 所有状态声明放在最顶部
  const [productData, setProductData] = useState(null);
  const [selectedDate, setSelectedDate] = useState(0);
  const [selectedTime, setSelectedTime] = useState(null);
  const [dates, setDates] = useState([]);
  const [availableTimeSlots, setAvailableTimeSlots] = useState([]);
  const [isLoading, setIsLoading] = useState(true); // 统一的加载状态

  // 时间段数据
  const baseTimeSlots = [
    "09:00-12:00",
    "12:00-14:00",
    "14:00-17:00",
    "17:00-18:00",
    "18:00-21:00"
  ];

  // 1. 计算未来7天日期 - 确保每次渲染都执行
  useEffect(() => {
    const calculateDates = () => {
      const result = [];
      const today = new Date();
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      
      for (let i = 0; i < 7; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        
        let weekdayLabel = '';
        if (i === 0) weekdayLabel = '今天';
        else if (i === 1) weekdayLabel = '明天';
        else if (i === 2) weekdayLabel = '后天';
        else weekdayLabel = weekdays[date.getDay()];

        result.push({
          weekday: weekdayLabel,
          day: `${date.getMonth() + 1}/${date.getDate()}`,
          name: weekdays[date.getDay()],
          fullDate: date,
          isPast: i < 0
        });
      }
      setDates(result);
    };

    calculateDates();
  }, []);

  // 2. 获取套餐数据 - 确保每次渲染都执行
  useEffect(() => {
    const fetchProduct = async () => {
      try {
        setIsLoading(true);
        if (!id) {
          Toast.show('套餐 ID 不存在');
          setIsLoading(false);
          return;
        }
        
        const response = await get_single_product_package(id);
        if (response.code === 0) {
          setProductData(response.data);
        } else {
          Toast.show(response.msg || '获取套餐数据失败');
        }
      } catch (err) {
        Toast.show('网络错误，获取套餐数据失败');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchProduct();
  }, [id]);

  // 3. 过滤可用时段 - 确保每次渲染都执行
  useEffect(() => {
    // 只有当dates有数据时才执行过滤逻辑
    if (dates.length === 0) return;

    const currentDate = dates[selectedDate];
    const isToday = selectedDate === 0;
    const currentHour = new Date().getHours();
    
    const filteredSlots = baseTimeSlots.filter((slot) => {
      if (!isToday) return true;
      
      const slotStartHour = parseInt(slot.split('-')[0].split(':')[0]);
      return slotStartHour >= currentHour;
    });

    setAvailableTimeSlots(filteredSlots);
    if (selectedTime !== null && !filteredSlots.includes(baseTimeSlots[selectedTime])) {
      setSelectedTime(null);
    }
  }, [selectedDate, dates]);

  // 处理日期选择
  const handleDateSelect = (index) => {
    if (dates[index]?.isPast) {
      Toast.show('不能选择过去的日期');
      return;
    }
    setSelectedDate(index);
  };

  // 处理时间选择
  const handleTimeSelect = (index) => {
    setSelectedTime(index);
  };

  // 处理预约确认
  const handleConfirmBooking = () => {
    if (dates.length === 0) return;
    
    if (selectedTime === null) {
      Toast.show('请选择预约时段');
      return;
    }

    const bookingInfo = {
      product: productData?.packageName || '肩颈深度调理套餐',
      date: dates[selectedDate],
      time: baseTimeSlots[selectedTime]
    };

    console.log('预约信息:', bookingInfo);
    Toast.show({
      content: '预约成功！',
      duration: 1500,
    });
    
    setTimeout(() => {
      navigate('/booking-success');
    }, 1500);
  };

  // 检查是否可以提交
  const isSubmitDisabled = () => {
    return selectedTime === null || dates.length === 0 || !productData;
  };

  // 加载状态判断 - 放在所有Hooks之后
  if (isLoading) {
    return <Load />;
  }

  // 数据异常处理
  if (!productData) {
    return (
      <div className="error-container">
        <h3>数据加载失败</h3>
        <button 
          className="retry-btn" 
          onClick={() => window.location.reload()}
        >
          重试
        </button>
        <button 
          className="back-btn" 
          onClick={() => navigate(-1)}
        >
          返回
        </button>
      </div>
    );
  }

  return (
    <div className="booking-container">
      {/* 头部导航 */}
      <header className="header">
        <div className="header-content">
          <ArrowLeftOutlined
            style={{ color: '#8B5A2B', fontSize: '20px', cursor: 'pointer' }}
            onClick={() => navigate(-1)}
          />
          <h1 className="header-title">选择预约时间</h1>
          <div></div>
        </div>
      </header>

      {/* 主内容区 */}
      <main className="main-content">
        {/* 预约项目信息 - 使用动态数据 */}
        <div className="product-card">
          <div className="product-info">
            <img
              src={productData.photo ? productData.photo.split(',')[0] : 'https://picsum.photos/id/237/200/200'}
              alt={productData.packageName || '肩颈深度调理套餐'}
              className="product-image"
              onError={(e) => e.target.src = 'https://picsum.photos/id/1005/200/200'}
            />
            <div className="product-details">
              <h2 className="product-title">{productData.packageName || '肩颈深度调理套餐'}</h2>
              <p className="product-description">{productData.description || '疏通肩颈经络，缓解肌肉僵硬'}</p>
              <div className="product-price">
                <span className="current-price">¥{productData.price}</span>
                {productData.originalPrice && (
                  <span className="original-price">
                    <StrikethroughOutlined style={{ fontSize: '14px' }} />
                    ¥{productData.originalPrice}
                  </span>
                )}
                <span className="duration-tag">{productData.duration || '60分钟'}</span>
              </div>
            </div>
          </div>
        </div>

        {/* 选择日期 */}
        <div className="section-container">
          <h3 className="section-title">选择日期</h3>
          <div className="date-container">
            {dates.map((date, index) => (
              <div
                key={index}
                className={`date-item ${selectedDate === index ? 'active' : ''} ${date.isPast ? 'disabled' : ''}`}
                onClick={() => handleDateSelect(index)}
                style={{ cursor: date.isPast ? 'not-allowed' : 'pointer' }}
              >
                <span className="date-weekday">{date.weekday}</span>
                <span className="date-day">{date.day}</span>
                <span className="date-name">{date.name}</span>
              </div>
            ))}
          </div>
        </div>

        {/* 选择时间段 */}
        <div className="section-container">
          <h3 className="section-title">选择时间</h3>
          <div className="time-container">
            {availableTimeSlots.length > 0 ? (
              availableTimeSlots.map((time, index) => {
                const originalIndex = baseTimeSlots.indexOf(time);
                return (
                  <div
                    key={originalIndex}
                    className={`time-slot ${selectedTime === originalIndex ? 'active' : ''}`}
                    onClick={() => handleTimeSelect(originalIndex)}
                  >
                    {time}
                  </div>
                );
              })
            ) : (
              <div className="no-time-slots">
                该日期暂无可用时段，请选择其他日期
              </div>
            )}
          </div>
        </div>
      </main>

      {/* 底部确认按钮 */}
      <div className="footer-button">
        <button
          className="confirm-button"
          onClick={handleConfirmBooking}
          disabled={isSubmitDisabled()}
          style={{ 
            opacity: isSubmitDisabled() ? 0.7 : 1,
            cursor: isSubmitDisabled() ? 'not-allowed' : 'pointer'
          }}
        >
          <span className="button-text">确认预约</span>
          <ArrowRightOutlined />
        </button>
      </div>
    </div>
  );
};

export default BookingTime;
